package com.strongbj.iot.devices.guis.respnose.handle;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.guis.message.GUISMessage;
import com.strongbj.iot.devices.guis.respnose.entity.DeviceOnlineEntity;
import com.strongbj.iot.devices.guis.respnose.message.GUISMQMessage;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

/**
 * 设备脱机的处理
 * @author yuzhantao
 *
 */
public class OfflineHandle implements IMessageHandle<GUISMessage, Object> {
	protected static Logger logger = LogManager.getLogger(OfflineHandle.class);
	protected static final String ONLINE_TOPIC = "daioReader";
	protected static final String ONLINE_COMMAND = "offline";
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");

	@Override
	public boolean isHandle(GUISMessage t) {
		return t.getCommand() == -99;
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, GUISMessage t) {
		
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
		String ip = insocket.getAddress().getHostAddress();
//		String deviceCode = ByteUtil.byteArrToHexString(t.getHostNumber());

		Map<String, Object> msgMag = new HashMap<>();
		msgMag.put("timestamp", System.currentTimeMillis());

		DeviceOnlineEntity eo = new DeviceOnlineEntity();
		eo.setIp(ip);
		
		GUISMQMessage mes = new GUISMQMessage();
		mes.setActioncode(ONLINE_COMMAND);
		mes.setRfidtype("smarrack");
		mes.setAwsPostdata(eo);

		topicSender.send(ONLINE_TOPIC, JSON.toJSONString(mes)); // 一会放到 mes上边
		logger.info("设备离线 ip={} JSON={}", ip,JSON.toJSONString(mes));
		return null;
	}

}
